//% color="#5bc2e8" iconWidth=50 iconHeight=40
namespace base64{
    //% block="初始化base64模块" blockType="command"
    export function base64_Iint(parameter: any, block: any) {
        Generator.addImport(`import base64\nfrom io import BytesIO\nfrom PIL import Image`)
        Generator.addCode(`
def frame2base64(frame):
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    img = Image.fromarray(frame) #将每一帧转为Image
    output_buffer = BytesIO() #创建一个BytesIO
    img.save(output_buffer, format='JPEG') #写入output_buffer
    byte_data = output_buffer.getvalue() #在内存中读取
    base64_data = base64.b64encode(byte_data) #转为BASE64
    return base64_data #转码成功 返回base64编码

def base642base64(frame):
    data=str('data:image/png;base64,')
    base64data = str(frame2base64(frame))
    framedata = base64data[2:(len(base64data)-1)]
    base642base64_data = data + str(framedata)
    return base642base64_data
def encode_image(filename):
    ext = filename.split(".")[-1]
    with open(filename, "rb") as f:
        img = f.read()
    data = base64.b64encode(img).decode()
    src = "data:image/{ext};base64,{data}".format(ext=ext, data=data)
    return src
def get_pic(base64_string):
    comma_index = base64_string.find(',')
    if comma_index != -1:
        base64_data = base64_string[comma_index + 1:]
        image_data = base64.b64decode(base64_data)

    else:
        raise ValueError("Base64 字符串格式不正确，缺少逗号分隔符")
    return image_data `)


}
    //% block="获取图像[DATA]转换base64编码后的字符串" blockType="reporter"
    //% DATA.shadow="normal" DATA.defl="frame"
    export function base64_Valve(parameter: any, block: any) {
        let data=parameter.DATA.code

        Generator.addCode(`base642base64(${data})`)

        
    } 

    //% block="获取图片[DATA]转换base64编码后的字符串" blockType="reporter"
    //% DATA.shadow="string" DATA.defl="picture.png"
    export function base64_Valvepicture(parameter: any, block: any) {
        let data=parameter.DATA.code

        Generator.addCode(`encode_image(${data})`)

        
    } 
    //% block="把base64编码后的字符串[STR]转换[IMG]图片" blockType="command"
    //% STR.shadow="string" STR.defl="data...iVBO.."
    //% IMG.shadow="string" IMG.defl="image.png"
    export function base64_Valvepicture1(parameter: any, block: any) {
        let data=parameter.STR.code
        let img=parameter.IMG.code

        Generator.addCode(`with open(${img}, 'wb') as f:
    f.write(get_pic(${data}))`)

        
    } 
}
